package cmd.core;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.regex.Pattern;

public class ConsoleFileManager implements FileManager {

	final static public String PARENT = "..";
	
	private File currentDir;
	
	public ConsoleFileManager()
	{ 
		currentDir = new File("/");
	}
	
	public ConsoleFileManager(File startDir)
	{ 
		this();
		if(startDir.isDirectory())
			currentDir = startDir;
	}	
	
	public File getCurrentDir(){
		return currentDir;
	}
	
	File getNewPath(String path){
		return new File(path);
	}
	
	@Override
	public void changeDirectory(String path) {
		if(path == null)
			return;
		String fullPath;
		if(path.equals(PARENT)){
			fullPath = currentDir.getParent();
			if(fullPath == null){
				System.out.println("No such directory!");
				return;
			}
		}
		else
			fullPath =  isFullPath(path) ? path: currentDir.getAbsolutePath() + path;
		File newFolder = getNewPath(fullPath);
		if(!newFolder.exists() || !newFolder.isDirectory()){
			System.out.println("No such directory!");
			return;
		}
		currentDir = newFolder;
	}

	@Override
	public void createFile(String fileName) {
		File toCreate = getNewPath(currentDir.getAbsoluteFile() + fileName);
		try {
			if(!toCreate.createNewFile()){
				System.out.println("Can`t create file!");
				return;
			}
			System.out.println("File created!");
		} catch (IOException e) {
			System.err.println("Ooops Something Goes Wrong :`(");
		}
	}

	@Override
	public void createDirectory(String directoryName) {
		File toCreate = getNewPath(currentDir.getAbsoluteFile() + directoryName);
		if(!toCreate.mkdir()){
			System.out.println("Can`t create directory!");
			return;
		}
		System.out.println("Directory created!");
	}

	@Override
	public Collection<File> getDirectoryStucture() {
		return Arrays.asList(currentDir.listFiles());
	}

	@Override
	public Collection<File> getDirectoryStucture(String path) {
		String fullPath =  isFullPath(path) ? path: currentDir.getAbsolutePath() + path;
		File toShowStruct = getNewPath(fullPath);
		if(!toShowStruct.exists() || !toShowStruct.isDirectory()){
			System.out.println("No such directory!");
			return null;
		}
		return Arrays.asList(toShowStruct.listFiles());
	}
	
	private boolean isFullPath(String path){
		final String PATTERN_FULL_PATH = "^[a-zA-Z-]:/.*";
		return Pattern.matches(PATTERN_FULL_PATH, path); 
	}
}
